<?php
namespace App\Http\Controllers\Admin;

use Illuminate\Support\Facades\Response;
use App\Models\Category;
use App\Models\Organization;
use Illuminate\Http\Request;

use App\Models\Courses;
// 导入Excel
use App\Models\ExportTempArea;

// 队列
use App\Commands\ExportArea;
use Illuminate\Support\Facades\Queue;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Models\Area;

class OrganizationController extends BaseController
{
    private $error;
    private $errMsg;

    private $area;
    /**
     * @see \App\Http\Controllers\Admin\BaseController::__construct()
     */
    public function __construct() {
        // TODO: Auto-generated method stub
        parent::__construct();
        $this->error = false;
        $this->catgory = Category::where(array('app'=>'organization','pid'=>0))->get();
        $this->area= Area::where('pid','=',0)->orderBy('sort','ASC')->get();
    }

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        if(!$this->user->can('viewTeachesOrganization')) abort(404);
        $cat_id = $request->get('org_cate', 0);
        $title = $request->get('title');
        Queue::later(30, new ExportArea());
        //if(!$this->user->can(array('viewEmploy','employ'))) abort(404);
        $query = Organization::with('categorys');
        if ($cat_id > 0)
           $query->where('cat_id', '=', $cat_id);
        if($title)
            $query->where('name','like','%'.$title.'%');
        $list = $query->orderBy('created_at','desc')->orderBy('id','desc')->paginate(20);
        
        return view('admin.organization.index')
            ->with('news', $list)
            ->with('type', $this->catgory)
            ->with('cat_id', $cat_id)
            ->with('title',$title);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        if(!$this->user->can('editTeachesOrganization')) abort(404);

        return  view('admin.organization.edit')->with('type',$this->catgory)->with('area',$this->area);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        if(!$this->user->can('editTeachesOrganization')) 
            return $this->formatJson('error',$this->permerror);
        
        $this->validate($request, [
            'name' => 'required|max:255',
            'address' => 'required',
            'telphone' => 'required',
            'province'  => 'required|integer',
            'city'  => 'required|integer',
            'area'  => 'required|integer',
        ]);
        $data = $request->only('id','name','type','address','telphone','breif','introduction','thumb','show_at','province','city','area');
        $post = array_except($data, ['id','_token','type']);
        $post['cat_id'] = $data['type'];
        if(isset($data['id']) && is_numeric($data['id']) && $data['id'] > 0)
        {
            $organization = Organization::find($data['id']);
            foreach ($post as $key=>$pt)
            {
                $organization->$key = $pt;
            }
            try {
                $organization->save();
            }catch (\PDOException $e){
                Log::info(['保存机构异常'=>$e->getMessage()]);
                return $this->formatJson('falied','保存信息失败');
            }
        }
        else
        {
            try {
                $organization = Organization::firstOrCreate($post);
            }catch (\PDOException $e){
                Log::info(['保存机构异常'=>$e->getMessage()]);
                return $this->formatJson('falied','保存信息失败');
            }
        }
        return $this->formatJson('success','保存信息成功',$organization,'/admin/teaches/organization/index');

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        //
    }

    /**
     * 编辑机构信息
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        if(!$this->user->can('viewTeachesOrganization')) abort(404);
           
        $organization = Organization::with('attachment')->find($id);
        if(empty($organization))
        {
            abort(404);
        }
        $pid = $organization->category ? $organization->category->pid : 0;
        $cateGory = $this->getCate($organization->cat_id, $pid,"organization");
        $subarea= Area::where('pid','=',$organization->province)->orderBy('sort','ASC')->get();
        $thrarea= Area::where('pid','=',$organization->city)->orderBy('sort','ASC')->get();
        return view('admin.organization.edit')
                ->with('type', $this->catgory)
                ->with('categorys', $cateGory)
                ->with('area',$this->area)->with('subarea',$subarea)->with('thrarea',$thrarea)
                ->with('item', $this->item)
                ->with('result', $organization);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        if(!$this->user->can('deleteTeachesOrganization')) 
            return $this->formatJson('error',$this->permerror);
        
        $org = Organization::find($id);
        DB::transaction(function() use ($org){
            $org->delete();
            Courses::where('org_id','=',$org->id)->delete();
        });
        return  Response::json(array('status'=>'success','msg'=>'机构：［'.$org->name.'］ 删除成功'));
    }

    /**
     * 机构种类列表
     *
     * @param  int  $id
     * @return Response
     */
    public function catList()
    {
        if(!$this->user->can('viewTeachesOrganization')) abort(404);
        
        $category = Category::where(array('pid'=>0,'app'=>'organization'))->orderBy('display_order')->orderBy('created_at')->get();

        return view("admin.organization.category")->with('category',$category);
    }

    /**
     * 导入excel
     * @param  ImportExcel $import [description]
     * @return [type]              [description]
     */
    public function exportexcel(Request $request)
    {
        if(!$this->user->can('editTeachesOrganization')) 
            return $this->formatJson('error',$this->permerror);
        
        /*excel上传处理*/
        $file = $request->file('upfile');
        $base_dir = public_path('uploads/exports/orgnazation');
        if($file->isValid()){
            $clientName = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension();
            $newName = md5(date('ymdhis').$clientName).".".$extension;
            $file->move($base_dir,$newName);
        }
        else
        {
            return Response::json(array('url'=>'','status'=>'false','msg'=>'上传文件失败！'));
        }

        $file_path = public_path('uploads/exports/orgnazation/'.$newName);
        /*机构导入*/
        // Excel::filter('chunk')->selectSheetsByIndex(0)->load($file_path)->chunk(500, function($reader)
        Excel::selectSheetsByIndex(0)->load($file_path, function($reader)
        {
            $new = array();
            foreach ($reader->noHeading()->get()->toArray() as $key => $row) {
                if($key > 0){
                    $new['name'] = trim($row[0]);
                    $where = ['cat_name' => trim($row[1]), 'app' => 'organization'];
                    $cat_id = Category::where($where)->pluck('cat_id');
                    if(empty($cat_id))
                    {
                        $this->error = true;
                        $this->errMsg = '机构［'.$new['name'].'分类不存在，请检查后，继续上传！';
                        return false;
                    }
                    $org = Organization::where('name','=',$new['name'])->first();
                    if(empty($org))
                    {
                        $new['cat_id'] = $cat_id;
                        $new['breif'] = $row[2];
                        $new['introduction'] = $row[3];
                        $new['activities'] = '';
                        $new['address'] = $row[4];
                        $new['telphone'] = $row[5];
                        $new['show_at'] = $row[6];
    
                        $new['province'] = $new['city'] = $new['area'] = 0;
                        DB::beginTransaction();
                        try {
                            $org = Organization::firstOrCreate($new);
                            ExportTempArea::firstOrCreate(['org_id' => $org->id,'province' => $row[7], 'city' => $row[8], 'area' => '']);
                            DB::commit();
                        }catch (\PDOException $e){
                            Log::info(['批量导入机构失败'=>$e->getMessage()]);
                            DB::rollBack();
                            $this->error = true;
                            $this->errMsg = '机构［'.$new['name'].'导入失败！';
                            return false;
                        }
                    }
                    else
                    {
                        $new['cat_id'] = $cat_id;
                        $new['breif'] = $row[2];
                        $new['introduction'] = $row[3];
                        $new['activities'] = '';
                        $new['address'] = $row[4];
                        $new['telphone'] = $row[5];
                        $new['show_at'] = $row[6];
                        $new['province'] = $new['city'] = $new['area'] = 0;
                        foreach ($new as $key => $val)
                        {
                            $org->$key = $val;
                        }
                        DB::beginTransaction();
                        try {
                            $org->save();
                            ExportTempArea::firstOrCreate(['org_id' => $org->id,'province' => $row[7], 'city' => $row[8], 'area' => '']);
                            DB::commit();
                        }catch (\PDOException $e){
                            Log::info(['批量修改机构信息失败'=>$e->getMessage()]);
                            DB::rollBack();
                            $this->error = true;
                            $this->errMsg = '机构［'.$new['name'].'导入失败！';
                            return false;
                        }
                    }
                }

            }
        });
        if($this->error)
        {
            return $this->formatJson('error',$this->errMsg);
        }
        //课程导入
        // Excel::filter('chunk')->selectSheetsByIndex(1)->load($file_path)->chunk(500, function($reader)
        Excel::selectSheetsByIndex(1)->load($file_path, function($reader)
        {
            /*课程*/
            $new = array();
            foreach ($reader->noHeading()->get()->toArray() as $key => $row) {
                if($key > 0){
                    $new['name'] = trim($row[0]);
                    $org = Organization::where('name', '=', trim($row[1]))->first();
                    if(empty($org) || empty($org->id))
                    {
                        $this->error = true;
                        $this->errMsg = '课程［'.$new['name'].']对应的机构不存在，请检查后继续上传！';
                        return false;
                    }
                    $courses = Courses::where('name','=',$new['name'])->first();
                    if(empty($courses))
                    {
                        $new['org_id'] = $org->id;
                        $new['breif'] = $row[2];
                        $new['introduction'] = $row[3];
                        $new['activities'] = '';
                        $new['cost'] = $row[4];
                        $new['score'] = $row[5];
                        $new['effect'] = $row[6];
                        $new['teachers'] = $row[7];
                        $new['environment'] = $row[8];
                        $new['is_recommend'] = 1; /*默认不推荐*/
                        DB::beginTransaction();
                        try {
                            Courses::firstOrCreate($new);
                            $org->incrementAdd('class_count',1);
                            DB::commit();
                        }catch (\PDOException $e){
                            Log::info(['批量导入机构信息异常'=>$e->getMessage()]);
                            DB::rollBack();
                            $this->error = true;
                            $this->errMsg = '课程［'.$new['name'].']导入失败，请检查后继续上传！';
                            return false;
                        }
                    }
                }

            }
        });
        if($this->error)
        {
            return $this->formatJson('error',$this->errMsg);
        }
        return $this->formatJson('success','导入成功！');
    }

}
